package br.usp.trabalho.sd.node;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import br.usp.trabalho.sd.InputAction;
import br.usp.trabalho.sd.StatusCode;



public class FileNodeServer implements Runnable
{
    public static final int PORT = 60050;

    private ServerSocket mServerSocket;
    private boolean      mRunning;

    private Client mMasterConnection;


    public FileNodeServer(Client client) throws IOException
    {
        this.mMasterConnection = client;

        mServerSocket = new ServerSocket(PORT);
        mRunning = true;
    }

    public void start()
    {
        new Thread(this).start();
    }
    
    public void stop()
    {
        mRunning = false;
    }

    @Override
    public void run()
    {
        while (mRunning)
        {
            try
            {
                // Only handles one connection per time
                Socket socket = mServerSocket.accept();

                ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

                switch ((InputAction) input.readObject())
                {
                case REMOVE:
                {
                    String fileName = readFileName(input, output);

                    mMasterConnection.removeFile(fileName);
                    // TODO
                    break;
                }

                case UPDATE:
                {
                    String fileName = readFileName(input, output);
                    // TODO
                    break;
                }

                case DOWNLOAD:
                {
                    String fileName = readFileName(input, output);
                    // TODO
                    break;
                }

                default:
                    break;
                }

                output.close();
                input.close();
                socket.close();
            }
            catch (ClassNotFoundException | IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private String readFileName(ObjectInputStream input, ObjectOutputStream output)
            throws IOException, ClassNotFoundException
    {
        // Request the file name
        output.writeObject(StatusCode.WAITING_FOR_FILENAME);
        output.flush();

        // Read the file name
        String fileName = (String) input.readObject();

        // Send the node info
        output.writeObject(StatusCode.OK);
        output.flush();
        
        return fileName;
    }
}
